package com.kust.smarthome.web.socketserver;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Service
public class SocketServer {
    private int port = 8001;
    private ServerSocket serverSocket;
    private ExecutorService executorService;// 线程池
    private final int POOL_SIZE = 100;

    public SocketServer() {
        try{
            serverSocket = new ServerSocket(port);
            executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void service() throws Exception {
        System.out.println("TCP通信服务启动！");
        while (true) {
            Socket socket = null;
            try {
                // 接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接
                socket = serverSocket.accept();
                //获得socket连接输出流
                InputStream in = socket.getInputStream();
                byte[] b=new byte[1024];
                int len = in.read(b);
                System.out.println("收到消息："+new String(b,0,len));
//                //获得socket连接输入流
//                ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());//获取输出流
//
//                if (message.getOperate().equals("login")) {
//                    Message message2 = new Message();
//                    message2.setTextmessage(logincheck(message));
//                    os.writeObject(message2);
//                    ManageClientThread.addClientThread(message.getTextmessage().split(",")[0],socket);
//                    executorService.execute(new Server(message.getTextmessage().split(",")[0],socket));
//                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
